package Util;

import domain.NingboGrowthRate;
import domain.ZhejiangPriceIndex;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ReadPriceIndex {
    private static SqlSessionFactory sqlSessionFactory;
    private static Reader reader;

    static {
        try {
            reader = Resources.getResourceAsReader("Configuration.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSession() {
        return sqlSessionFactory;
    }

    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        ArrayList<List> a = new ArrayList();
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String temp = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            SqlSession session = sqlSessionFactory.openSession();
            dao.ZhejiangPriceIndexMapper userOperation = session.getMapper(dao.ZhejiangPriceIndexMapper.class);
            while ((temp = reader.readLine()) != null) {
                String s[] = temp.split("\t");
                ZhejiangPriceIndex zhejiangPriceIndex = new ZhejiangPriceIndex();
                zhejiangPriceIndex.setId(0);
                zhejiangPriceIndex.setCity(s[0]);
                for(int i = 1;i<=3;i++){
                    if(i == 1)
                        zhejiangPriceIndex.setType("总体消费指数");
                    if(i == 2)
                        zhejiangPriceIndex.setType("食品");
                    if(i == 3)
                        zhejiangPriceIndex.setType("衣着");
                    zhejiangPriceIndex.setValue(Double.parseDouble(s[i]));
                    zhejiangPriceIndex.setYear(s[4]);
                    zhejiangPriceIndex.setConsumeOrPrice(s[5]);
                    userOperation.insert(zhejiangPriceIndex);
                    session.commit();
                }
            }
            session.close();
        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

    }

    public static void main(String[] args) {
        String fileName = "C:\\Users\\admin\\Desktop\\a.txt";
        ReadPriceIndex.readFileByLines(fileName);
    }
}
